<template>
  <div class="set-operations">
    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Plus /></el-icon> 添加集合元素</span>
        </div>
      </template>
      <el-form :model="saddForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="saddForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="saddForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSAdd" :icon="Plus">添加</el-button>
          <el-button @click="resetAddForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Remove /></el-icon> 移除集合元素</span>
        </div>
      </template>
      <el-form :model="sremForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="sremForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="sremForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleSRem" :icon="Remove">移除</el-button>
          <el-button @click="resetRemForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Search /></el-icon> 获取集合所有元素</span>
        </div>
      </template>
      <el-form :model="smembersForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="smembersForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSMembers" :icon="Search">获取所有</el-button>
          <el-button @click="resetMembersForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="smembersResult.length > 0 || smembersResultEmpty" class="result-box">
        <div class="result-header">
          <h4>结果:</h4>
          <el-button type="text" @click="copyMembersResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="smembersResult.length === 0 && smembersResultEmpty"
          title="集合为空或不存在"
          type="warning"
          :closable="false"
          show-icon
        />
        <el-tag 
          v-else 
          v-for="(item, index) in smembersResult" 
          :key="index"
          class="result-tag"
          effect="plain"
        >
          {{ item }}
        </el-tag>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Check /></el-icon> 检查元素是否存在</span>
        </div>
      </template>
      <el-form :model="sismemberForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="sismemberForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="sismemberForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSIsMember" :icon="Search">检查</el-button>
          <el-button @click="resetIsMemberForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="sismemberResult !== null" class="result-box">
        <div class="result-header">
          <h4>结果:</h4>
        </div>
        <el-alert
          :title="sismemberResult ? '元素存在于集合中' : '元素不存在于集合中'"
          :type="sismemberResult ? 'success' : 'info'"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Delete /></el-icon> 删除集合</span>
        </div>
      </template>
      <el-form :model="deleteForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="deleteForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleDelete" :icon="Delete">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Remove, Search, Refresh, Delete, Check, CopyDocument } from '@element-plus/icons-vue'
import { sAdd, sRem, sMembers, sIsMember, del } from '../api/redis'

const saddForm = reactive({
  key: '',
  value: ''
})

const sremForm = reactive({
  key: '',
  value: ''
})

const smembersForm = reactive({
  key: ''
})

const sismemberForm = reactive({
  key: '',
  value: ''
})

const deleteForm = reactive({
  key: ''
})

const smembersResult = ref<string[]>([])
const smembersResultEmpty = ref(false)
const sismemberResult = ref<boolean | null>(null)

const handleSAdd = async () => {
  if (!saddForm.key || !saddForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    const response = await sAdd(saddForm.key, [saddForm.value])
    if (response.data.success) {
      ElMessage.success(response.data.message || '添加成功')
      resetAddForm()
    } else {
      ElMessage.error(response.data.error || '添加失败')
    }
  } catch (error: any) {
    console.error('SADD error:', error)
    ElMessage.error(error.response?.data?.error || error.message || '添加失败')
  }
}

const handleSRem = async () => {
  if (!sremForm.key || !sremForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    const response = await sRem(sremForm.key, [sremForm.value])
    if (response.data.success) {
      ElMessage.success(response.data.message || '移除成功')
      
      // 如果当前正在查询的键和值被移除，更新结果
      const currentKey = sremForm.key
      const currentValue = sremForm.value
      
      resetRemForm()
      
      if (smembersForm.key === currentKey) {
        handleSMembers()
      }
      if (sismemberForm.key === currentKey && sismemberForm.value === currentValue) {
        sismemberResult.value = false
      }
    } else {
      ElMessage.error(response.data.error || '移除失败')
    }
  } catch (error: any) {
    console.error('SREM error:', error)
    ElMessage.error(error.response?.data?.error || error.message || '移除失败')
  }
}

const handleSMembers = async () => {
  if (!smembersForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await sMembers(smembersForm.key)
    smembersResult.value = response.data || []
    smembersResultEmpty.value = true
    
    if (smembersResult.value.length === 0) {
      ElMessage.warning('集合为空或不存在')
    } else {
      ElMessage.success('获取成功')
    }
  } catch (error) {
    ElMessage.error('获取失败')
    smembersResult.value = []
    smembersResultEmpty.value = false
  }
}

const handleSIsMember = async () => {
  if (!sismemberForm.key || !sismemberForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    const response = await sIsMember(sismemberForm.key, sismemberForm.value)
    if (response.data.success) {
      sismemberResult.value = response.data.isMember
      ElMessage.success(response.data.message || '检查成功')
    } else {
      ElMessage.error(response.data.message || '检查失败')
      sismemberResult.value = null
    }
  } catch (error: any) {
    console.error('SISMEMBER error:', error)
    ElMessage.error(error.response?.data?.message || error.message || '检查失败')
    sismemberResult.value = null
  }
}

const handleDelete = async () => {
  if (!deleteForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    await del(deleteForm.key)
    ElMessage.success('删除成功')
    deleteForm.key = ''
    
    // 如果当前正在查询的键被删除，清空结果
    if (smembersForm.key === deleteForm.key) {
      smembersResult.value = []
      smembersResultEmpty.value = false
    }
    if (sismemberForm.key === deleteForm.key) {
      sismemberResult.value = null
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const resetAddForm = () => {
  saddForm.key = ''
  saddForm.value = ''
}

const resetRemForm = () => {
  sremForm.key = ''
  sremForm.value = ''
}

const resetMembersForm = () => {
  smembersForm.key = ''
  smembersResult.value = []
  smembersResultEmpty.value = false
}

const resetIsMemberForm = () => {
  sismemberForm.key = ''
  sismemberForm.value = ''
  sismemberResult.value = null
}

const copyMembersResult = () => {
  if (smembersResult.value.length > 0) {
    navigator.clipboard.writeText(JSON.stringify(smembersResult.value, null, 2))
    ElMessage.success('已复制到剪贴板')
  }
}
</script>

<style scoped>
.set-operations {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.operation-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.operation-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 5px;
}

.result-box {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.result-header h4 {
  margin: 0;
}

.result-tag {
  margin: 5px;
  padding: 6px 10px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .set-operations {
    grid-template-columns: 1fr;
  }
}
</style>